package com.xinhe.web.util;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xinhe.web.entity.WeixinConfig;
import com.xinhe.web.reposity.ValueConfigRepository;
import com.xinhe.web.reposity.WeixinConfigRepository;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
@Slf4j
@Component
public class HttpUtil {
    @Autowired
    private ValueConfigRepository valueConfigRepository;
    @Autowired
    private WeixinConfigRepository weixinConfigRepository;

    private static final String DOMAIN_NAME = "https://api.mch.weixin.qq.com";
    private static final String SEARCH_TRANSFER_BATCHES_URL = "/v3/transfer/batches/out-batch-no/%s/details/out-detail-no/%s";
    public static final String WECHAT_PAY_SERIAL_NO = "6B4127DB1756E63BA32AE1914E1D6BE561CB8E60";
    public static final String PRIVATE_KEY_PATH = "/root/apiclient_key.pem";
    public static String postTransBatRequest(String requestUrl, String requestJson, String wechatPayserialNo, String mchID4M, String privatekeypath) {
        CloseableHttpClient httpclient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        try {
            HttpPost httpPost = new HttpPost(requestUrl);
            httpPost.addHeader("Content-Type", "application/json");
            httpPost.addHeader("Accept", "application/json");
            httpPost.addHeader("Wechatpay-Serial", wechatPayserialNo);
            String strToken = VechatPayV3Util.getToken("POST", "/v3/transfer/batches", requestJson, mchID4M, wechatPayserialNo, privatekeypath);
            log.error("微信转账token " + strToken);
            httpPost.addHeader("Authorization", "WECHATPAY2-SHA256-RSA2048 " + strToken);
            httpPost.setEntity((HttpEntity)new StringEntity(requestJson, "UTF-8"));
            response = httpclient.execute((HttpUriRequest)httpPost);
            entity = response.getEntity();
            log.info("-----getHeaders.R equest-ID:" + response.getHeaders("Request-ID"));
            return EntityUtils.toString(entity);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {}
        return null;
    }

    public JSONObject searchTransBatRequest(String outBatchNo, String outDetailNo) {
        Long weixin_config_id_mini_program = Long.valueOf(valueConfigRepository.findById("weixin_config_id_mini_program").get().getValue());
        WeixinConfig weixinConfig = this.weixinConfigRepository.findById(weixin_config_id_mini_program).get();
        if (weixinConfig == null) {
            log.error("微信配置异常");
            return null;
        }
        String url = String.format("https://api.mch.weixin.qq.com/v3/transfer/batches/out-batch-no/%s/details/out-detail-no/%s", new Object[] { outBatchNo, outDetailNo });
        try {
            String path = String.format("/v3/transfer/batches/out-batch-no/%s/details/out-detail-no/%s", new Object[] { outBatchNo, outDetailNo });
            Map<String, Object> params = new HashMap<>();
            Map<String, Object> headers = new HashMap<>();
            String strToken = VechatPayV3Util.getToken("GET", path, null,
                    weixinConfig.getMchId(), "6B4127DB1756E63BA32AE1914E1D6BE561CB8E60",
                    "/root/apiclient_key.pem");
            log.error("微信转账token " + strToken);
            headers.put("Authorization", "WECHATPAY2-SHA256-RSA2048 " + strToken);
            headers.put("Accept", "application/json");
            JSONObject jsonObject = HttpClientUtil.requestGet(url, params, headers);
            System.out.printf("查询转账记录：outBatchNo：%s,outDetailNo：%s,数据：%s", new Object[] { outBatchNo, outBatchNo, jsonObject });
            return jsonObject;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
